const app = getApp()
Page({
  data: {
    url: app.apiroot,
    loading: true,
    page:0,
    active:0,
    nav:[],
    news:[],
  },

  //生命周期函数--监听页面加载
  onLoad: function (options) {
    let that= this;
    that.navApi();
  },

  //生命周期函数--监听页面初次渲染完成
  onReady: function () {
    this.setData({
      skeleton: false,
    })
  },
  // 下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      page: 0,
      loading: true,
      news: []
    });
    wx.showNavigationBarLoading();
    //停止下拉刷新
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 1500);
    that.newsApi();
  },
  //上拉加载
  onReachBottom: function () {
    var that = this;
    this.newsApi();
  },
  //点击切换
  navApi: function (e) {
    let that = this;
    var active = that.data.active;
    app.api().Get('api/v1/allwin-news-cate',function (result) {
      if (result.code = 200){
        that.setData({
          nav: result.data,
          cate_id: result.data[active].id,
        });
        that.newsApi();
      }
    })
  },
  //点击新闻
  newsApi: function () {
    let that = this;
    if (that.data.loading) {
      var page = that.data.page + 1;
      var cate_id = that.data.cate_id;
      app.api().Get('api/v1/allwin-news-lists', {cate_id: cate_id, page: page }, function (result) {
        if (result.code == 200) {
          var news = that.data.news;
          for (let i in result.data) {
            news.push(result.data[i]);
          }
          that.setData({
            news: news,
            page: page,
          });
        }
        that.setData({
          loading: false
        })
      })
    }
  },
  //内容阅读
  onNews: function (e) {
    let that = this;
    var id = e.currentTarget.id;
    var config = wx.getStorageSync('config');
    wx.navigateTo({
      url: '/pages/helper/webview?src=' + that.data.url + '/wechat-' + config.app_id + '/allwin-news-review/' + id,
    })
  },
  //点击加载更多
  onChange: function (event){
    var active = event.detail.index,nav = this.data.nav;
    this.setData({
      page: 0,
      loading: true,
      news: [],
      cate_id: nav[active].id,
    });
    this.newsApi();
  }
})